<template>
	<view class="u-p-t-30">
		<view class="bg-white">
			<u-field v-model="mobile" label="新手机号" placeholder="请输入新手机号">
			</u-field>
			<u-field v-model="code" label="验证码" placeholder="请输入验证码">
				<u-button size="mini" slot="right" type="primary" @click="getCode" hover-class="none">{{codeText}}</u-button>
			</u-field>
			<u-verification-code ref="uCode" @change="codeChange"></u-verification-code>
		</view>
		<view class="sub-btn">
			<u-button shape="circle" type="primary" @click="submit" hover-class="none">确定</u-button>
		</view>
	</view>
</template>

<script>
	import common from '@/utils/wxApplet/common.js'
	export default {
		data() {
			return {
				mobile: '',
				code: '',
				codeText: '',
			}
		},
		onLoad() {

		},
		methods: {
			codeChange(text) {
				this.codeText = text;
			},
			getCode() {
				if (!this.mobile) {
					this.$u.toast('请输入手机号');
					return;
				}
				if (!this.$u.test.mobile(this.mobile)) {
					this.$u.toast('请输入正确的手机号');
					return;
				}
				if (this.$refs.uCode.canGetCode) {
					// 模拟向后端请求验证码
					uni.showLoading({
						title: '正在获取验证码'
					})
					this.$u.api.getVerifyCode({
						phone: this.mobile
					}).then(res => {
						uni.hideLoading();
						// 通知验证码组件内部开始倒计时
						this.$refs.uCode.start();
						this.$u.toast('已发送');
					}).catch(err => {
						console.log(err);
					})
				} else {
					this.$u.toast('倒计时结束后再发送');
				}
			},
			submit() {
				if (!this.mobile) {
					this.$u.toast('请输入手机号');
					return;
				}
				if (!this.$u.test.mobile(this.mobile)) {
					this.$u.toast('请输入正确的手机号');
					return;
				}
				if (!this.code) {
					this.$u.toast('请输入验证码');
					return;
				}
				if (this.code.length < 6) {
					this.$u.toast('验证码至少为6位数');
					return;
				}
				this.$u.api.changePhone({
					phone: this.mobile,
					captcha: this.code
				}).then(res => {
					this.$u.toast("手机号更改成功")
					common.getUserInfo().then(res => {
						uni.navigateBack()
					})
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.sub-btn {
		margin-top: 110rpx;
		padding: 0 30rpx;
	}
</style>